
package com.pig4cloud.pig.common.data.tenant;

import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.security.tenant.TenantContextHolder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chengang
 * @date 2021/9/11
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextHolderFilter extends GenericFilterBean {

	@Autowired
	private TenantConfigProperties tenantProperties;

	@Override
	@SneakyThrows
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		String tenantId = request.getHeader(SecurityConstants.TENANT_ID);

		//获取接口路径
		String servletPath = request.getServletPath();

		log.debug("获取header中的租户ID为:{}，接口路径：{}", tenantId, servletPath);

		//带cps
		if(servletPath.indexOf(SecurityConstants.CPS_ROLE_URl) >=0) {
			TenantContextHolder.setTenantId(tenantProperties.getCpsTenantId());
		}else{
			if (StrUtil.isNotBlank(tenantId)) {
				TenantContextHolder.setTenantId(Integer.parseInt(tenantId));
			}else{
				TenantContextHolder.setTenantId(SecurityConstants.TENANT_ID_1);
			}
		}


		filterChain.doFilter(request, response);
		//该filter最优先，请求处理后最后执行，之后再清楚租户
		TenantContextHolder.clear();
	}
}
